import React from 'react'
import { connect } from 'dva';
import {
  Button, Icon, Radio, Form, Row, Col, Input, Upload, message
} from 'antd';
import './Images.scss';
import Uploaddd from './UploadImg';
import { UrlConfig } from "../../../services/fetch";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

@connect(({ add }) => ({
  add: add
}))
class Images extends React.PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      radioValue: 1,
      index: 0,
      marginLeft: 0,
      marginRight: 0,
      imgList: [{
        key: 0,
        img_path: '',
        img_title: '',
        img_intro: ''
      }],
      titleLength: 0,
      titleValue: '',
      keyLength: 0,
      introLength: 0,
      num: 0
    }
  }

  componentDidMount() {
    this.props.onRef(this)
    window.PubSub.subscribe('imgAll', this.setImgAll)
  }
  componentWillUnmount() {
    this.props.dispatch({ type: 'add/resetPushClick' })
  }
  onChangeRadio = (e) => {
    this.setState({
      radioValue: e.target.value
    });
    if (e.target.value == 1) {
      this.setFields(
        {
          url: ''
        }
      );
    }
  }
  /**
   * 获取title length
   */
  getTitleLength = (e) => {
    let length = e.target.value.length
    if (length <= 60) {
      this.setState({
        titleLength: length,
        titleValue: e.target.value
      })
    }
    window.PubSub.publish('tabTitle', e.target.value)
  }
  /**
   * 增加列表
   */
  addImgList = () => {
    let imgArr = [...this.state.imgList]
    let index = this.state.num;
    imgArr.push({
      key: index + 1,
      img_path: '',
      img_title: '',
      img_intro: ''
    });
    this.setState({
      imgList: imgArr,
      num: index + 1
    });
    this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })

    // console.log(index);

  }

   /**
   * 上移
   */
  moveUp = (index) => {
    let imgArr = [...this.state.imgList]

    imgArr.map((item, indexs) => {
      if (item.key == index) {
        let idx = indexs
        if(idx==0){
          idx = 1
        }
        let su = imgArr.splice(indexs, 1)
        console.log(idx)
        imgArr.splice(idx-1,0,su[0])
      }
    })
    this.setState({
      imgList: imgArr,
    });
    this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })
  }

   /**
   * 下移
   */
  moveDown = (index) => {
    console.log(index)
    let imgArr = [...this.state.imgList]

    for(let i = 0;i<imgArr.length;i++){
      if(imgArr[i].key==index){
        let idx = i
        if(idx==this.state.num){
          idx=idx-1
        }
        let su = imgArr.splice(i, 1)
        imgArr.splice(idx+1,0,su[0])
        break
      }
    }
    this.setState({
      imgList: imgArr,
    });
    this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })
  }

  /**
   * 删除列表
   */
  deletImgList = (index) => {
    let imgArr = [...this.state.imgList]

    imgArr.map((item, indexs) => {
      if (item.key == index) {
        imgArr.splice(indexs, 1)
      }
    })
    this.setState({
      imgList: imgArr,
      num: this.state.num - 1
    });
    this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })
  }
  /**
   * 设置值
   */
  setListInput = (e, key) => {
    let imgArr = [...this.state.imgList]
    imgArr.map((item, index) => {
      if (item.key === key) {
        item.img_title = e.target.value
      }
    })
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })
  }
  setListText = (e, key) => {
    let imgArr = [...this.state.imgList]
    imgArr.map((item, index) => {
      if (item.key === key) {
        item.img_intro = e.target.value
      }
    })
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })
  }
  setListUrl = (data, key) => {
    let imgArr = [...this.state.imgList]
    imgArr.map((item, index) => {
      if (item.key === key) {
        item.img_path = data
      }
    })
    console.log(imgArr, '123123132')
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })
  }
  /**
   * 关闭
   */
  close = (key) => {
    this.props.dispatch({
      type: 'add/close',
      key: key
    })
  }
  /**
   * 推荐左滑按钮
   */
  left = () => {
    let marginLeft = this.state.marginLeft + 145;
    if (marginLeft >= 0) {
      this.setState({
        marginLeft: 0
      })
    } else {
      this.setState({
        marginLeft: marginLeft
      })
    }
  }

  /**
   * 推荐右滑按钮
   */
  right = () => {
    let marginLeft = this.state.marginLeft - 145;
    let length = (this.props.add.gltjData.length - 4) * 145
    if (marginLeft <= (-length)) {
      this.setState({
        marginLeft: -length
      })
    } else {
      this.setState({
        marginLeft: marginLeft
      })
    }
  }
  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue()
    let about = []
    this.props.add.gltjData.map((item, index) => {
      about.push(item.information_id)
    })
    data["about"] = about.join()
    data["img_arr"] = this.state.imgList
    data["type"] = 2;
    return data
  }
  getFieldsValue = () => {
    let data = this.props.form.getFieldsValue()
    this.props.form.validateFields()
    let validateArr = this.props.form.getFieldsError()
    let isDown = true
    for (const key in validateArr) {
      if (validateArr.hasOwnProperty(key)) {   //判断是否有效验错误
        if (validateArr[key]) {
          isDown = false
          return
        }
      }
    }
    if (isDown) {
      let about = []
      this.props.add.gltjData.map((item, index) => {
        about.push(item.information_id)
      })
      data["about"] = about.join()
      data["img_arr"] = this.state.imgList
      data["type"] = 2
      return data
    }
  }
  /**
   * 重置表单
   */
  resetFields = () => {
    this.props.form.resetFields()
    this.setState({
      titleValue: ''
    })
  }
  /**
   * 设置表单值
   */
  setFields = (data) => {
    this.props.form.setFieldsValue(data)
    this.setState({
      titleValue: data.information_title
    })
    if (data.url) {
      this.setState({
        radioValue: 2
      })
    }else{
      this.setState({
        radioValue: 1
      })
    }
    if (data.img_arr && data.img_arr.length) {
      let arr = []
      data.img_arr.map((item, index) => {
        arr.push({
          key: index,
          img_path: item.img_path,
          img_title: item.img_title,
          img_intro: item.img_intro
        })
      });
      this.setState({
        imgList: arr,
        num: arr.length
      });
      this.props.dispatch({ type: 'add/setUploadImageList', data: arr })
    }
    if (data.about) {
      this.props.dispatch({ type: 'add/setPushClick', data: data.about_list })
    }
  }
  /**
  * 订阅
  */
  setImgAll = (data) => {
    if (data.type === 'biz_sobey_picture') {
      let imgList = [...this.state.imgList]
      let length = imgList.length
      let num = this.state.num
      if (num < length) {
        imgList[num].img_path = data.keyFrameUrl
        this.setState({
          num: num + 1,
          imgList: imgList
        });
        this.props.dispatch({ type: 'add/setUploadImageList', data: imgList })
      } else {
        imgList[0].img_path = data.keyFrameUrl
        this.setState({
          num: 1
        })
      }

    }
  }
  /**
   * 从内容库选择
   */
  getfromContent = () => {
    if (window.bar) {
      window.bar.show('picture', 'ggsc');//图片
      this.props.dispatch({ type: 'add/saveMchType', data: 'imgAll' })
    }
  }

  // 添加多图
  addImgListMore = () => {
    let imgArr = [...this.state.imgList]
    let index = this.state.num;
    let changeImgList = (url) => {
     const newItem = url.map((i,idx) => (
        {
          key: index + 1 + idx,
          img_path: i,
          img_title: '',
          img_intro: ''
        }
      ))

      imgArr = [...imgArr,...newItem]
      this.setState({
        imgList: imgArr,
        num: index + url.length
      });
      this.props.dispatch({ type: 'add/setUploadImageList', data: imgArr })
    }
    let fcUpload = (key) => {
      window.fc = new window.FcUpload({
        elem: 'fcUpload',
        oss: this.props.add.configJson.aliyunOssSwitch,       //是否为oss 上传
        multiple: true,  //是否允许上传多个文件
        type: 'img', // 上传文件类型\ img 图片，  video 视频
        actionImg: `${UrlConfig}/fcpublic/uploads/uploadImg`,  //本地上传图片地址
        actionVideo: `${UrlConfig}/fcpublic/uploads/uploadVideo`,  //本地上传视频地址
        actionOss: this.props.add.configJson.actionOss,  //后端认证接口，获取临时上传凭证
        endpoint: this.props.add.configJson.endpoint,
        bucket: this.props.add.configJson.bucket,
        customDomain: this.props.add.configJson.customDomain,
        ossConfig: this.props.add.configJson,
        callback: (callRes) => {
          let url;
          if (callRes.oss) {  // oss 和本地返回数据结构不一样
            url = callRes.response;
          } else {
            url = callRes.response.data;
          }
          changeImgList(url)
          console.log(url);
        }
      })

      window.fc.show();
    }
    fcUpload()
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const myValidateFields = (rule, values, callback) => {
      var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
      if (values) {
        if (!reg.test(values)) {
          callback('请输入正确的URL')
        }
      }
      callback()
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 },
      },
    };
    let gltjData = this.props.add.gltjData;
    if (!gltjData) {
      gltjData = [];
    }

    //将当前this传递给父类
    this.props.onRef(this);

    return (
      <div className="Images">
        <Form className='mon_form' style={{ paddingTop: 20, paddingLeft: 20 }}>
          <Row gutter={24} >
            {/* 图集 标题 */}
            <Col span={6}>
              <div className='flex_box' style={{display: 'flex'}}>
                  <FormItem
                    label="ᠭᠠᠷᠴᠠᠭ"
                  >
                    <p className="title_show">
                      {/* <span className="required" >*</span> */}
                      {getFieldDecorator('information_title', {
                        rules: [{
                          required: true, message: 'ᠵᠢᠷᠤᠭ ᠲᠡᠭᠦᠪᠦᠷᠢ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ᠎ᠢᠶᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ',
                        }],
                      })(
                        <Input placeholder="ᠵᠢᠷᠤᠭ ᠲᠡᠭᠦᠪᠦᠷᠢ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ᠎ᠢᠶᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" className="artical_title" onChange={this.getTitleLength}
                          size="large" maxLength={250} />
                      )}
                      <span className="rightInput">{this.state.titleLength}/250</span>
                    </p>
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠭᠡ"
                  >
                    {getFieldDecorator('key_words')(
                      <Input className="keyInput key_words" placeholder='ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠭᠡ᠎ᠪᠡᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ' onChange={e => {
                        let data = e.target.value
                        if (data.length <= 250) {
                          this.setState({
                            keyLength: data.length,
                          })
                        }
                      }} maxLength={250} />
                    )}
                    <span className="showKeyLength_img">{this.state.keyLength}/250</span>
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="ᠲᠣᠪᠴᠢᠯᠠᠯ"
                  >
                    {getFieldDecorator('intro')(
                      <TextArea placeholder="ᠲᠣᠪᠴᠢᠯᠠᠯ᠎ᠢᠶᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" autosize={{ minRows: 2, maxRows: 6 }} className="introInput"
                        onChange={e => {
                          let data = e.target.value
                          if (data.length <= 1000) {
                            this.setState({
                              introLength: data.length
                            })
                          }
                        }} maxLength={1000} />
                    )}
                    <span className="showTextLength">{this.state.introLength}/1000</span>
                  </FormItem>
                  <RadioGroup className='mon_radio_group' onChange={this.onChangeRadio} value={this.state.radioValue} style={{ marginBottom: '10px' }}>
                    <Radio value={1}>ᠨᠠᠢᠷᠠᠭᠤᠯᠬᠤ ᠬᠡᠪ</Radio>
                    <Radio value={2}>URL ᠬᠡᠪ</Radio>
                  </RadioGroup>

                  {this.props.add.configJson.mchSwitch ? <Button className='select_for_content_btn mon_btn' style={this.state.radioValue === 2 ? { display: "none" } : {}} onClick={this.getfromContent}>ᠠᠭᠤᠯᠭ᠎ᠠ᠎ᠶᠢᠨ ᠬᠥᠮᠥᠷᠭᠡ᠎ᠡᠴᠡ ᠰᠣᠩᠭᠣᠬᠤ</Button> : ''}
                  <span mon_class='mon_label' style={this.state.radioValue === 2 ? { display: "none" } : { position: 'relative', left: '-30px' }}>
                    ᠲᠠᠢᠯᠪᠤᠷᠢ᠄ 1- 15 ᠵᠢᠷᠤᠭ ᠳᠠᠮᠵᠢᠭᠤᠯᠤᠭᠠᠷᠠᠢ᠂ ᠵᠢᠷᠤᠭ᠎ᠤᠨ ᠬᠡᠮᠵᠢᠶ᠎ᠡ᠎ᠨᠢ 2 M᠎ᠡᠴᠡ ᠬᠡᠲᠦᠷᠡᠵᠦ ᠪᠣᠯᠬᠤ᠎ᠦᠭᠡᠢ᠂ ᠬᠡᠯᠪᠡᠷᠢ᠎ᠨᠢ jpg/ png
                  </span>
                  <FormItem mon_class='mon_label' label="">
                    {getFieldDecorator('url', {
                      rules: [{
                        validator: myValidateFields
                      }]
                    })(
                      <Input  mon_class='mon_label' placeholder="url ᠬᠣᠯᠪᠤᠭᠠᠰᠤ᠎ᠪᠡᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ" style={this.state.radioValue === 1 ? { display: "none" } : {}} />
                    )}
                  </FormItem>
              </div>
            </Col>
            {/* 添加 图集 */}
            <Col span={18}>
              <div className='imgListBox' style={this.state.radioValue === 2 ? { display: "none" } : { }}>
                {
                  this.state.imgList.map((item, index) => {
                    return (
                      <div className="imgList" key={item.key}>
                        <div className="img_upload">
                          <Uploaddd setUrl={(data) => this.setListUrl(data, item.key)} img={item.img_path} />
                        </div>

                        <div className="imgList_right">
                          <Row gutter={24}>
                            <Col span={6}>
                              <div class='flex_column_start' >
                                <div class='mon_word'>ᠵᠢᠷᠤᠭ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ：</div> 
                                <Input mon_class='mon_input' style={{height: '400px'}} value={item.img_title}
                                  onChange={(e) => this.setListInput(e, item.key)} />
                              </div>
                            </Col>
                            <Col span={18}>
                              <div className="imgList_text">
                                <div class='mon_word'>ᠵᠢᠷᠤᠭ᠎ᠤᠨ ᠳᠦᠷᠰᠦᠯᠡᠯ：</div>
                                <TextArea mon_class='mon_input' placeholder="ᠵᠢᠷᠤᠭ᠎ᠤᠨ ᠳᠦᠷᠰᠦᠯᠡᠯ" style={{ height: '400px' }} value={item.img_intro}
                                  onChange={(e) => this.setListText(e, item.key)} autosize={{ minRows: 14, maxRows: 6 }} />
                              </div>
                            </Col>
                          </Row>
                          
                          <span className="delet_imgList" style={{bottom:'120px'}} onClick={() => this.deletImgList(item.key)}>ᠬᠠᠰᠤᠬᠤ</span>
                          <span className="delet_imgList" style={{right: '-5px', bottom:'70px'}} onClick={() => this.moveUp(item.key)}>ᠵᠡᠭᠦᠨᠱᠢ ᠱᠢᠯᠵᠢᠬᠦ</span>
                          <span className="delet_imgList" style={{right: '-5px'}} onClick={() => this.moveDown(item.key)}>ᠪᠠᠷᠠᠭᠤᠨᠱᠢ ᠱᠢᠯᠵᠢᠬᠦ</span>
                        </div>
                      </div>
                    )
                  })
                }
                <div className="add_box">
                  <div className="add_imgList" onClick={this.addImgList}>
                    <Icon type="plus" theme="outlined" />ᠨᠢᠭᠡ ᠵᠢᠷᠤᠭ ᠨᠡᠮᠡᠬᠥ
                  </div>
                  <div className="add_imgList_more" onClick={this.addImgListMore}>
                    <Icon type="plus" theme="outlined" />ᠤᠯᠠᠨ ᠵᠢᠷᠤᠭ ᠨᠡᠮᠡᠬᠥ
                  </div>
                </div>
              </div>
            </Col>
          </Row>
        </Form>
        
        <h3 className='mon_wrap_text'>ᠮᠡᠳᠡᠭᠡ ᠵᠠᠩᠭᠢ᠎ᠶᠢᠨ ᠲᠠᠨᠢᠯᠴᠠᠭᠤᠯᠭ᠎ᠠ</h3>
        <div className="gl-video">
          <div className="gl-left" onClick={this.left}><Icon type="left" theme="outlined" /></div>
          <div className="gl-main">
            <div className="gl-content" style={{ marginLeft: this.state.marginLeft }}>
              {gltjData.map((item, key) => {
                return (
                  <div className="gl-item">
                    <img className="" src={item.thumbnail} />
                    <div className="gl-title">{item.video_title}</div>
                    <div className="close" onClick={() => {
                      this.close(key)
                    }}><Icon className="delete" type="delete" theme="outlined" /></div>
                  </div>
                )
              })}
            </div>
          </div>
          <div className="gl-right" onClick={this.right}><Icon type="right" theme="outlined" /></div>
        </div>
      </div>
    )
  }
}

const ImagesFrom = Form.create()(Images);
export default ImagesFrom;



